package com.hbue.water.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbue.water.entity.Account;
import com.hbue.water.mapper.AccountMapper;
import com.hbue.water.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author yushu
 * @date 2021/12/23
 * @apiNate
 */
@Service
@Slf4j
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    /**
     * 用户登录
     * 步骤：
     * 1 根据用户名查询对应的账户信息
     * 2 判断账户是否为空，如果为空登录失败，返回false
     * 3 如果账户非空，对用户输入的密码进行MD5加密
     * 4 比较数据库的密码和加密的密码是否相等
     * 5 如果相等，登录成功返回true，否则，登录失败返回false
     *
     * @param
     * @return true登录成功，false登录失败
     */
    @Override
    public boolean login(String userName, String userPwd) {
        log.info("userName = "+userName+" userPwd = "+userPwd);
        QueryWrapper<Account> qw = new QueryWrapper<>();
        qw.eq("user_name",userName);
        // 根据用户名查询对应的账号信息
        Account account = accountMapper.selectOne(qw);
        if (null == account) {
            return false;
        }
        // 对表单输入的密码进行MD5加密
        String encodePwd = DigestUtil.md5Hex(userPwd);
        // 比较数据库密码和加密的密码是否相等，条件成立：登录成功，否则登录失败
        if (Objects.equals(encodePwd,account.getUserPwd())) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean saveAccount(Account account) {
        QueryWrapper<Account> qw = new QueryWrapper<>();
        qw.eq("user_name", account.getUserName());
        Account acc = accountMapper.selectOne(qw);
        if (acc != null) {
            return false;
        } else {
            String userPwd = account.getUserPwd();
            String encodingPwd = DigestUtil.md5Hex(userPwd);
            account.setUserPwd(encodingPwd);
            accountMapper.insert(account);
            return true;
        }
    }
}
